package com.example.admin.gridview;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

public class GridView extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        setTitle("网格视图");
        android.widget.GridView gv=(android.widget.GridView)findViewById(R.id.grid_view);
        gv.setAdapter(new ImageAdapter(this));
    }

    public class ImageAdapter extends BaseAdapter{
        private Context mContext;
        public ImageAdapter(Context c){
            mContext=c;
        }
        private Integer[] mThumbIds={
                R.drawable.grid_view_01,R.drawable.grid_view_02,
                R.drawable.grid_view_03,R.drawable.grid_view_04,
                R.drawable.grid_view_05,R.drawable.grid_view_06,
                R.drawable.grid_view_07,R.drawable.grid_view_08,
                R.drawable.grid_view_09,R.drawable.grid_view_10,
                R.drawable.grid_view_11,R.drawable.grid_view_12,
                R.drawable.grid_view_13,R.drawable.grid_view_14,
                R.drawable.grid_view_15,
                R.drawable.sample_1,R.drawable.sample_2,R.drawable.sample_3,
                R.drawable.sample_4,R.drawable.sample_5,R.drawable.sample_6,
                R.drawable.sample_7
        };

        //获取图片的数目
        public int getCount(){
            return mThumbIds.length;
        }

        //获取图片在库中的位置
        public Object getItem(int arg0){
            return null;
        }

        //获取图片的ID
        public long getItemId(int arg0){
            return 0;
        }

        public View getView(int position, View convertView,ViewGroup parent){
            ImageView imageView;
            if(convertView==null){
                imageView=new ImageView(mContext);

                //设置imageView的大小
                imageView.setLayoutParams(new android.widget.GridView.LayoutParams(250,250));

                //设置刻度的类型,按比例扩大图片的size居中显示，使得图片长(宽)等于或大于View的长(宽)
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

                //设置间距
                imageView.setPadding(8,8,8,8);
            }
            else{
                imageView=(ImageView)convertView;
            }

            imageView.setImageResource(mThumbIds[position]);//为ImageView设置图片资源
            return imageView;
        }
    }
}